package com.jmye.coding.util.excel;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: jmye
 * @date: 2025/7/4 13:37
 **/
@Slf4j
public class ExcelUtils {


    /**
     * 导出 Excel
     *
     * @param response  响应
     * @param list      数据集合
     * @param fileName  文件名 eg: aa.xlsx
     * @param sheetName Sheet 名称
     * @param pojoClass 数据实体类型
     */
    public static void exportExcel(HttpServletResponse response, List<?> list, String fileName, String sheetName, Class<?> pojoClass) {
        try {

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            fileName = new String(fileName.getBytes(), StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            EasyExcel.write(response.getOutputStream(), pojoClass)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet(sheetName)
                    .doWrite(list);
        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            log.info("导出失败!", e);
            throw new RuntimeException("导出失败!");
        }
    }

    /**
     * 导出 Excel
     *
     * @param response  响应
     * @param fileName  文件名 eg: aa.xlsx
     * @param sheetName Sheet 名称
     * @param headList  动态表头
     * @param data      动态数据
     */
    public static void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<String> headList, List<List<String>> data) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);


            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            fileName = new String(fileName.getBytes(), StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);


            EasyExcel.write(response.getOutputStream())
                    .autoCloseStream(Boolean.FALSE)
                    .head(setHead(headList))
                    .sheet(sheetName)
                    .registerWriteHandler(new CustomWidthStyleStrategy(1))
                    .doWrite(data);

        } catch (Exception e) {
            throw new RuntimeException("下载失败", e);
        }
    }

    private static List<List<String>> setHead(List<String> headList) {
        return headList.stream().map(head -> {
            List<String> list = new ArrayList<>();
            list.add(head);
            return list;
        }).collect(Collectors.toList());
    }

}
